const Router = require("express").Router;
const {assign, forIn} = require("lodash");
const LocalFetcher = require("./local");
const localFetcher = new LocalFetcher();
const fs = require("fs");
const path = require("path");
const router = new Router();
const {mock, responseWrapper} = require("../data-factory");

let mockData = [];
fs.readdirSync(path.join(__dirname, "../data-maps")).forEach(function (file) {
	mockData = mockData.concat(require("../data-maps/" + file))
});

mockData.map(item => {
	const {url, template, routes} = item;
	router.post(
		url,
		function (req, res) {
			const params = req.body;
			return new Promise(function (resolve) {
				setTimeout(function () {
					let resData = getMockData(template, routes, params);
					resolve(resData)
				}, Math.random() * 1000) // 1 秒的延时
			}).then(function (data) {
				res.status(200).json(responseWrapper(data))
			})
		});
});

function getMockData(template, routes, params) {
	if (!routes || routes.length === 0) {
		return mock(template)
	} else {
		for (let i = 0; i < routes.length; i++) {
			const route = routes[i];
			let match = true;
			forIn(route.params, function (value, key) {
				if (params[key] !== value) match = false
			});
			if (match) return mock(route.template)
		}
		return mock(template)
	}
}

router.post("/login", function (req, res) {
	return res.status(200).json(responseWrapper({}))
});

router.post("/custom-login", function (req, res) {
	return res.status(200).json(responseWrapper({}))
});

module.exports = router;
